package com.ecommerce.web.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.ecommerce.dal.entity.Customer;
import com.ecommerce.dal.service.ICustomerManagerService;
import com.ecommerce.web.validator.CustomerRegistrationValidator;

/**
 * @author Belal, Etch
 */

@Controller
@RequestMapping("/CustomerRegistration.htm")
public class CustomerRegistrationController {

	@Autowired
	private ICustomerManagerService customerManagerService;
	
	@Autowired
	@Qualifier("customerRegistrationValidator")
	private Validator customerRegistrationValidator;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView initForm(Map<String, Object> map) {
		Customer customer = new Customer();
		java.util.Date todayDate = new java.util.Date();
		customer.setJoinDate(todayDate);
		customer.setBirthDate(todayDate);
		// command object
		map.put("customer", customer);
		// return form view
//		return "CustomerRegistration";
		return new ModelAndView("CustomerRegistration", map);
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(@ModelAttribute("customer") Customer customer,
			BindingResult result, SessionStatus status) {
		customerRegistrationValidator.validate(customer, result);
		if (result.hasErrors()) {
			// if validator failed
			return "CustomerRegistration";
		} else {
			status.setComplete();
			java.util.Date todayDate = new java.util.Date();
			customer.setJoinDate(todayDate);
			//calling the service to persist the customer
			customerManagerService.saveCustomer(customer);
			
			// form success
			return "CustomerSucessRegistration";
		}
	}
	
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(
	            dateFormat, false));
	}
}
